package cn.dankal.flyaudio;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.kongzue.dialog.v2.SelectDialog;
import com.yzq.zxinglibrary.common.Constant;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.concurrent.ExecutionException;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentTabHost;
import androidx.lifecycle.Observer;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import api.ChatServiceFactory;
import api.ScanServiceFactory;
import cn.dankal.basiclib.DKUserManager;
import cn.dankal.basiclib.base.BaseView;
import cn.dankal.basiclib.pojo.BaseResponse;
import cn.dankal.basiclib.pojo.RegisterJpushEntity;
import cn.dankal.basiclib.pojo.ScanCarModel;
import cn.dankal.basiclib.pojo.ScanResultEntity;
import cn.dankal.basiclib.protocol.MainProtocol;
import cn.dankal.basiclib.rx.AbstractSubscriber;
import cn.dankal.basiclib.util.ActivityUtils;
import cn.dankal.basiclib.util.JMessageToastUtils;
import cn.dankal.basiclib.util.ToastUtils;
import cn.dankal.basiclib.util.image.PicUtils;
import cn.dankal.basiclib.widget.CommonDialog;
import cn.dankal.basiclib.widget.TipDialog;
import cn.dankal.business.Constants;
import cn.dankal.flyaudio.contract.LoginContractHelper;
import cn.dankal.flyaudio.database.UserEntry;
import cn.dankal.flyaudio.entity.Event;
import cn.dankal.flyaudio.entity.EventType;
import cn.dankal.flyaudio.friend.pickimage.StringUtil;
import cn.dankal.flyaudio.login.LoginActivity;
import cn.dankal.flyaudio.model.FlyUser;
import cn.flyaudio.phonecontrol.mycar.main.MyCarMainFragment;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.model.UserInfo;
import cn.jpush.im.api.BasicCallback;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

@Route(path = MainProtocol.MAIN)
public class TabMainActivity extends AppCompatActivity implements BaseView {

    private FragmentTabHost tabHost;
    protected TipDialog loadingDialog;

    private Class[] fragments = {EyeFragment.class, FriendFragment.class,
            MyCarMainFragment.class
            , StoreFragment.class, NewPersonalFragment.class,};

    private int[] tabHostImg = {R.drawable.ic_tab_eye, R.drawable.ic_tab_friend,
            R.drawable.ic_tab_car, R.drawable.ic_tab_store, R.drawable.ic_tab_user};

    private String[] tabHostText = {"探索", "朋友", "爱车", "优品", "我的"};
    private CompositeDisposable mDisposables = new CompositeDisposable();

    private void link() {
    }

    public LoginBoradCast loginBoradCast = new LoginBoradCast();

    public class LoginBoradCast extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(LoginContractHelper.LOGIN_SUCCESS)) {
                FlyUser flyUser = new FlyUser();
                flyUser.setToken(DKUserManager.getUserToken().getToken());
                flyUser.setUuid(DKUserManager.getUserInfo().getUserUuid());
                LoginContractHelper.saveLoginUserInfo(TabMainActivity.this, flyUser);
                Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tab_main);
//        DankalApplication.setLogin(true);
//        int currentUser = SharePreferenceManager.getCurrentUser();
//        TestData.setUser(currentUser);
//        IntentFilter intentFilter = new IntentFilter();
//        intentFilter.addAction(LoginContractHelper.LOGIN_SUCCESS);
//        LocalBroadcastManager.getInstance(this).registerReceiver(loginBoradCast, intentFilter);

        if (!DKUserManager.isLogined()) {
            startActivity(new Intent(this, LoginActivity.class));
            finish();
            return;
        }
        tabHost = findViewById(R.id.tab_host);
        tabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
        int tabSize = fragments.length;
        for (int i = 0; i < tabSize; i++) {
            TabHost.TabSpec tabSpec = tabHost.newTabSpec(tabHostText[i]).setIndicator(getTabItemView(i));
            //将Tab按钮添加进Tab选项卡中
            tabHost.addTab(tabSpec, fragments[i], null);
            //设置Tab按钮的背景
            tabHost.getTabWidget().getChildAt(i).setBackgroundResource(R.color.white);
        }
        tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
            @Override
            public void onTabChanged(String tabId) {
                tabHost.getCurrentView().setSelected(true);
            }
        });
        LiveEventBus.get("to_home_activity", String.class).observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                tabHost.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        tabHost.setCurrentTab(0);
                        LiveEventBus.get("to_home_activity1", String.class).post("1");
                    }
                },200);

//                tabHost.getCurrentView().setSelected(true);
            }
        });
//        getPassword();
    }

    private void getPassword() {
        showLoadingDialog();
        ChatServiceFactory.initialization()
                .subscribe(new AbstractSubscriber<BaseResponse<RegisterJpushEntity>>(this) {
                    @Override
                    public void onNext(BaseResponse<RegisterJpushEntity> registerJpushEntityBaseResponse) {
                        JMessageClient.login(registerJpushEntityBaseResponse.getData().getUser().getUsername(), registerJpushEntityBaseResponse.getData().getUser().getPassword(), new BasicCallback() {
                            @Override
                            public void gotResult(int responseCode, String LoginDesc) {
                                dismissLoadingDialog();
                                if (responseCode == 0) {
                                    LoginContractHelper.sendLoginBoardCast(TabMainActivity.this);
                                    UserInfo userInfo = JMessageClient.getMyInfo();
                                    String username = userInfo.getUserName();
                                    String appKey = userInfo.getAppKey();
                                    userInfo.setNickname(DKUserManager.getUserInfo().getName());
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            try {
                                                if (!StringUtil.isEmpty(DKUserManager.getUserInfo().getAvatar())) {
                                                    File mFile = Glide.with(TabMainActivity.this).asFile().load(PicUtils.getUrl(DKUserManager.getUserInfo().getAvatar())).submit().get();
                                                    JMessageClient.updateUserAvatar(mFile, new BasicCallback() {
                                                        @Override
                                                        public void gotResult(int i, String s) {

                                                        }
                                                    });
                                                }
                                            } catch (InterruptedException e) {
                                                e.printStackTrace();
                                            } catch (ExecutionException e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }).start();
                                    JMessageClient.updateMyInfo(UserInfo.Field.nickname, userInfo, new BasicCallback() {
                                        @Override
                                        public void gotResult(int i, String s) {

                                        }
                                    });
                                    UserEntry user = UserEntry.getUser(username, appKey);
                                    if (null == user) {
                                        user = new UserEntry(username, appKey);
                                        user.save();
                                    }
                                } else {
                                    Toast.makeText(getApplicationContext(), "登录失败", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    }
                });
    }

    /**
     * 给Tab按钮设置图标和文字
     */
    private View getTabItemView(int index) {
        View view = getLayoutInflater().inflate(R.layout.tab_item_view, null);
        ImageView imageView = view.findViewById(R.id.imageview);
        imageView.setImageResource(tabHostImg[index]);
        TextView textView = view.findViewById(R.id.textview);
        textView.setText(tabHostText[index]);
//        ScreenAdapterTools.getInstance().loadView(view);
        return view;
    }

    public void showLoadingDialog() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
            loadingDialog = null;
        }
        loadingDialog = new TipDialog.Builder(this)
                .setIconType(TipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("正在加载")
                .create();
        loadingDialog.show();
    }

    public void dismissLoadingDialog() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

    @Override
    public void showToast(String message) {
        ToastUtils.showShort(message);
    }

    @Override
    public void tokenInvalid() {
        CommonDialog.Builder builder = new CommonDialog.Builder(this);
        builder.setTitle("您的飞歌账号在其他设备上通过飞歌密码登录，如果这不是你的操作，你的飞歌密码已经泄露，请修改飞歌密码")
                .setPositiveButton("确定", Color.parseColor("#141414"), type -> {
                    DKUserManager.resetToken();
                    DKUserManager.resetUserInfo();
                    ActivityUtils.finishAllActivities();
                    try {
                        startActivity(new Intent(this,
                                Class.forName(getString(cn.dankal.basiclib.R.string.login_activity_path))));
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    builder.getDialog().dismiss();
                })
                .create()
                .show();
    }

    @Override
    public void addNetworkRequest(Disposable d) {
        mDisposables.add(d);
    }

    @Override
    public void finishActivity() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(loginBoradCast);
        if (mDisposables != null) mDisposables.clear();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.SCAN && resultCode == RESULT_OK && data != null) {
            //扫码内容
            String result = data.getStringExtra(Constant.CODED_CONTENT);
            if (result.contains("native://cn.dankal.flyaudio/activityid=")) {
                String resultValue = result.split("native://cn.dankal.flyaudio/activityid=")[1];
                ARouter.getInstance().build(MainProtocol.ACTIVITY_DETAIL)
                        .withString(Constants.UUID, resultValue)
                        .navigation();
                return;
            } else {
                if (result.contains("jpush_group_id")) {
                    String groupId = result.split("=")[1];
                    JMessageClient.applyJoinGroup(Integer.valueOf(groupId), "", new BasicCallback() {
                        @Override
                        public void gotResult(int i, String s) {
                            EventBus.getDefault().post(new Event.Builder().setType(EventType.refreshConversationList)
                                    .build());
                            JMessageToastUtils.errorToast(i);
                        }
                    });
                    return;
                }
                if (result.contains("onlyNumber")) {
                    ScanCarModel scanCarModel = new ScanCarModel();
                    scanCarModel.setOnlyNumber(getValueByTag(result, "onlyNumber"));
                    scanCarModel.setBodyColor(getValueByTag(result, "bodyColor"));
                    scanCarModel.setCarInterior(getValueByTag(result, "carInterior"));
                    scanCarModel.setKeyOne(getValueByTag(result, "keyOne"));
                    scanCarModel.setKeyTwo(getValueByTag(result, "keyTwo"));
                    scanCarModel.setTyre(getValueByTag(result, "tyre"));
                    scanCarModel.setVinCode(getValueByTag(result, "vinCode"));
                    Log.d("TabMainActivity", JSON.toJSONString(scanCarModel));
                    if (scanCarModel != null) {
                        if (!TextUtils.isEmpty(scanCarModel.getOnlyNumber())) {
                            //绑定车主http://test.frp.flyaudio.cn/controlcar/frontapi/carInfo/saveCarInfo
                            doBindCar(scanCarModel);
                        }
                    }
                } else {
                    if (!TextUtils.isEmpty(result)) {
                        //绑定车主http://test.frp.flyaudio.cn/controlcar/frontapi/carInfo/saveCarInfo
                        //tag:flyAudioCarInfo;uuid:xxxx;
                        if(result.contains("flyAudioCarInfo")){
                            //扫码登录
                            doScanLogin(getValueByTag(result,"uuid"), "0");
                        }
                    }
                }
//                ToastUtils.showShort("暂无相关信息");
            }
        }
    }

    private String getValueByTag(String text, String tag) {
        String[] s = text.split(";");
        for (String str : s) {
            if (str.contains(tag)) {
                return str.replaceAll(tag + ":", "");
            }
        }
        return "";
    }

    private String currentUuid = "dd";

    /**
     * {
     * "msg": "success",
     * "code": 200,
     * "data": {
     * "msg": "success",
     * "flag": "10000",
     * "tag": "flyAudioCarInfo",
     * "value": "cd479bdd88604943951bae9e3efd907f"
     * }
     * }
     *
     * @param uuid
     * @param status
     */
    public void doScanLogin(String uuid, String status) {
        Log.d("TabMainActivity", uuid);
        if(!DKUserManager.isLogined()){
            ToastUtils.showShort("未登录!");
            return;
        }
        this.currentUuid = uuid;
        String url = "frontuser/frontapi/appUser/sweepCodeLogin/" + uuid + "/" + status;
        ScanServiceFactory.scanLogin(url)
                .subscribe(new AbstractSubscriber<ScanResultEntity>(this) {
                    @Override
                    public void onNext(ScanResultEntity userInfoBean) {
                        if (!TextUtils.equals(userInfoBean.getData().getMsg(), "验证码已过期") && TextUtils.equals(status, "0")) {
                            showHander();
                        } else {
                            ToastUtils.showShort(userInfoBean.getData().getMsg());
                        }
                        Log.d("TabMainActivity", JSON.toJSONString(userInfoBean));
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        Log.d("TabMainActivity", JSON.toJSONString(e));
                    }
                });
    }

    private void showHander() {
        SelectDialog.show(TabMainActivity.this, "提示", "是否同意该设备登录", "同意", (dialog, which) -> {
            doScanLogin(currentUuid, "1");
        }, "拒绝", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                doScanLogin(currentUuid, "2");
            }
        });
    }

    public void doBindCar(ScanCarModel scanCarModel) {
        ScanServiceFactory.login(scanCarModel)
                .subscribe(new AbstractSubscriber<Object>(this) {
                    @Override
                    public void onNext(Object userInfoBean) {
                        Log.d("TabMainActivity", JSON.toJSONString(userInfoBean));
                    }
                });
    }
    //    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
//        super.onActivityResult(requestCode, resultCode, data)
//        if (requestCode == Constants.SCAN && resultCode == RESULT_OK && data != null) {
//
//            //扫码内容
//            val result = data.getStringExtra(Constant.CODED_CONTENT)
//
//            if (result.contains("native://cn.dankal.flyaudio/activityid=")) {
//                val resultValue = result.split("native://cn.dankal.flyaudio/activityid=")[1]
//                ARouter.getInstance().build(MainProtocol.ACTIVITY_DETAIL)
//                        .withString(Constants.UUID, resultValue)
//                        .navigation()
//                return
//            } else {
//                showToast("暂无相关信息")
//            }
//        }
//    }
}
